package com.fjwt.gz.mch.ctrl.score.record;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.ScoreRecordTotalVO;
import com.fjwt.gz.mch.ctrl.CommonCtrl;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * 积分记录（领取消耗）
 */
@Slf4j
@RestController
@RequestMapping("/api/scoreRecord")
public class ScoreRecordController extends CommonCtrl {

    @Autowired
    private ScoreRecordTotalService recordTotalService;

    @Autowired
    private AgentScoreRuleService agentScoreRuleService;

    @Autowired
    private FansService fansService;

    @Autowired
    private FansPayService fansPayService;

    @Autowired
    private FansAwardService fansAwardService;

    @Autowired
    private OldFansInfoService oldFansInfoService;

    @Autowired
    private AgentScoreService agentScoreService;

    /**
     * 用户领取积分
     */
    @PostMapping("/save")
    public ApiRes recordSave(){
        Long fansId = getCurrentUser().getFansId();
//        String appId = getCurrentUser().getAppId();
        String appId = request.getHeader("appid");
        Long ruleId = getValLong("ruleId");
        log.info("fans端会员积分领取接口调用，请求地址：/api/scoreRecord/save，请求参数：fanId：{} ，ruleId：{}，appId：{}",fansId,ruleId,appId);
        if(Objects.isNull(fansId) || Objects.isNull(ruleId)){
            return ApiRes.customFail("网络故障，请稍后重试！");
        }

        String cacheKey = CS.getCacheKeyFansScoreSign(CS.SYS_ROLE_TYPE.MCH, fansId);
        log.info("cacheKey:{}",cacheKey);
        boolean signInResult = RedisUtil.setIfAbsent(cacheKey, "", 30);
        log.info("result:{}",signInResult);
        if (!signInResult) {
            log.info("请勿重复签到");
            throw new BizException("请勿重复签到");
        }

        try {
            AgentScoreRuleEntity ruleEntity = agentScoreRuleService.getById(ruleId);
            if(ObjectUtils.isEmpty(ruleEntity) || 0 == ruleEntity.getState()){
                return ApiRes.customFail("积分规则不存在！");
            }
            JSONObject json = recordTotalService.checkSign(fansId, ruleId , Constants.SCORE.RULE);
            //解析json中flag字段的值   flag=false 表示已领取
            Boolean flag = json.getBoolean("flag");
            if(!flag){
                return ApiRes.customFail("已领取，请勿重复领取！");
            }
            FansEntity fansEntity = fansService.getById(fansId);
            if(null == fansEntity){
                throw new BizException("该用户不存在！");
            }
            int result = recordTotalService.scoreRecordGenerate(fansId,ruleId,ruleEntity.getScoreRuleName(),Constants.SCORE.RULE,null, appId);
            if(result > 0){
                return ApiRes.ok();
            }else{
                return ApiRes.customFail("操作失败！");
            }
        } catch (Exception e) {
            if (e instanceof BizException) {
                throw (BizException) e;
            }else {
                log.error("签到异常：", e);
                throw new BizException("签到异常");
            }
        }
    }

    /**
     * 用户积分兑换
     */
    @PostMapping("/exchange")
    public ApiRes recordExchange(){
        Long fansId = getCurrentUser().getFansId();
        String locationAgentNo =request.getHeader("locationAgentNo");
//        String appId = getCurrentUser().getAppId();
        String appId = request.getHeader("appid");
        String scoreExchangeId = getValString("scoreExchangeId");
        Integer infoType = getValInteger("infoType");
        Integer state = getValInteger("state");
        String name = getValString("name");
        log.info("C端会员积分兑换接口调用，请求地址：/api/scoreRecord/exchange，请求参数：会员id：{} ，积分兑换id：{}，类型：{}，名称：{}，locationAgentNo:{}，appId:{}，state：{}",fansId,scoreExchangeId,infoType,name,locationAgentNo,appId,state);
        if(fansId == null || StringUtils.isEmpty(scoreExchangeId) || infoType == null || StringUtils.isEmpty(name) ){
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
/**
 *
 *
 * 郑州区域临时关闭
 *
 */
//        recordTotalService.checkOffScore(fansId,"主动过期", appId);
        if (state == null){
            String date = LocalDateTime.now().minusMinutes(5)
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Integer i1 = fansAwardService.selectRecord(date, fansId, scoreExchangeId, infoType);
            if (i1 == 1){
                return ApiRes.fail(ApiCodeEnum.LITE_USER_REPEAT_RECORD);
            }
        }
        int i = recordTotalService.scoreRecordDestroy(fansId, scoreExchangeId, infoType, name, locationAgentNo, appId);
        if(i > 0){
            return ApiRes.ok();
        }else{
            return ApiRes.customFail("操作失败！");
        }
    }

    /**
     * 校验用户券是否发券
     * @return
     */
    @PostMapping("/checkUserPayAuth")
    public ApiRes checkUserPayAuth(){
        Long fansId = getCurrentUser().getFansId();
        String scoreExchangeId = getValString("scoreExchangeId");
        log.info("fans端获取用户券是否发券接口调用，请求地址：/api/scoreRecord/checkUserPayAuth，请求参数：会员id：{} ，券id：{}",fansId,scoreExchangeId);
        JSONObject object = fansPayService.checkUserPayAuth(fansId, scoreExchangeId);
        log.info("fans端获取用户券是否发券接口，请求地址：/api/scoreRecord/checkUserPayAuth，返回结果{}",JSONUtil.toJsonStr(object));
        return ApiRes.ok(object);
    }

    /**
     * 用户新增，消耗积分记录
     * 新增0
     * 消耗1
     */
    @PostMapping("/recordList")
    public ApiRes recordList(){
        Long fansId = getCurrentUser().getFansId();
        String appId = getCurrentUser().getAppId();
        String flag = getValString("flag");
        log.info("fans端获取用户积分记录接口调用，请求地址：/api/scoreRecord/recordList，请求参数：会员id：{} ，flag：{} ，appId：{}",fansId,flag, appId);
        IPage<ScoreRecordTotalVO> page = recordTotalService.findFansScoreRecord(getIPage(),fansId, flag, appId);
        log.info("fans端获取用户积分记录接口，请求地址：/api/scoreRecord/recordList，返回结果{}",JSONUtil.toJsonStr(page));
        return ApiRes.page(page);
    }

    /**
     * 获取用户签到记录
     * @return
     */
    @PostMapping("/getSignList")
    public ApiRes getSignList(){
        Long fansId = getCurrentUser().getFansId();
        Long ruleId = getValLong("ruleId");
        String time = getValString("time");
        String infoType = "RULE"; //getValString("infoType");
        log.info("fans端获取用户签到记录接口调用，请求地址：/api/scoreRecord/getSignList，请求参数：会员id：{} ，规则id：{}，类型：{}，时间：{}",fansId,ruleId,infoType,time);
        List<ScoreRecordTotalEntity> list = recordTotalService.findSignRecordList(fansId, ruleId, infoType, time);
        List<ScoreRecordTotalVO> voList = list.stream().map(e -> {
            ScoreRecordTotalVO vo = BeanUtil.copyProperties(e, ScoreRecordTotalVO.class);
            return vo;
        }).toList();
        log.info("fans端获取用户签到记录接口调用，请求地址：/api/scoreRecord/getSignList，返回结果：{}",JSONUtil.toJsonStr(voList));
        return ApiRes.ok(voList);
    }

    /**
     * 获取用户兑换积分商城兑换记录
     * @return
     */
    @PostMapping("/getExchangeScore")
    public ApiRes getExchangeScore(){
        Long fansId = getValLong("fansId");
        String flag = getValString("flag");
        log.info("fans端获取用户积分商城兑换记录接口调用，请求地址：/api/scoreRecord/getExchangeScore，请求参数：会员id：{} ，flag：{}",fansId,flag);
        IPage<ScoreRecordTotalEntity> list = recordTotalService.getExchangeScore(getIPage(), fansId, flag);
        log.info("fans端获取用户积分商城兑换记录接口调用，请求地址：/api/scoreRecord/getExchangeScore，返回结果：{}",JSONUtil.toJsonStr(list));
        return ApiRes.page(list);
    }

    /**
     * 检验签到
     */
    @PostMapping("/checkSign")
    public ApiRes checkSign(){
        Long fansId = getCurrentUser().getFansId();
        Long infoId = getValLong("infoId");
        log.info("fans端会员签到接口调用，请求地址：/api/scoreRecord/checkAuth，请求参数：会员id：{} ，签到id：{}",fansId,infoId);
        JSONObject json = recordTotalService.checkSign(fansId, infoId, Constants.SCORE.RULE);
        log.info("fans端会员签到接口调用，请求地址：/api/scoreRecord/checkAuth，返回结果：{}", JSONUtil.toJsonStr(json));
        return ApiRes.ok(json);
    }

    /**
     * 检验实名
     */
    @PostMapping("/checkAuth")
    public ApiRes checkAuth(){
        Long fansId = getValLong("fansId");
        String infoType = getValString("infoType");
        log.info("fans端检验实名接口调用，请求地址：/api/scoreRecord/checkAuth，请求参数：会员id：{} ，类型：{}",fansId,infoType);
        JSONObject json = recordTotalService.checkAuth(fansId, infoType);
        log.info("fans端检验实名接口调用，请求地址：/api/scoreRecord/checkAuth，返回结果：{}", JSONUtil.toJsonStr(json));
        return ApiRes.ok(json);
    }

//    /**
//     * 获取当天获得福分总量
//     * @return
//     */
//    @PostMapping("/getUserScoreSum")
//    public ApiRes getUserScoreSum(){
//        Long fansId = getCurrentUser().getFansId();
//        log.info("fans端获取当天获得福分总量接口调用，请求地址：/api/scoreRecord/getUserScoreSum，请求参数：会员id：{}",fansId);
//        int userScoreSum = recordTotalService.getUserScoreSum(fansId);
//        log.info("fans端获取当天获得福分总量接口返回，请求地址：/api/scoreRecord/getUserScoreSum，会员id：{}，返回结果：{}",fansId,userScoreSum);
//        return ApiRes.ok(userScoreSum);
//    }

    /**
     * 历史福分迁移
     * @return
     */
    @PostMapping("/oldScoreMove")
    public ApiRes oldScoreMove(){
        Long fansId = getCurrentUser().getFansId();
        Long userId = getCurrentUser().getUserId();
        String appId = getCurrentUser().getAppId();
//        String appId = request.getHeader("appid");
        String locationAgentNo =request.getHeader("locationAgentNo");
        String openId = getValString("openId");
        log.info("历史福分迁移请求参数：openId:{},fansId:{},客户id：{}, agentNo:{}",openId,fansId,userId,locationAgentNo);
        if(null == fansId || null == userId || StringUtils.isEmpty(openId) || StringUtils.isEmpty(locationAgentNo)){
            return ApiRes.customFail("网络故障，请稍后重试！");
        }

        AgentScoreEntity agentScoreByAgentNo = agentScoreService.getAgentScoreByAgentNo(locationAgentNo);
        if (ObjectUtils.isEmpty(agentScoreByAgentNo)){
            return ApiRes.customFail("未查询到福分机构类别！");
        }

        LambdaQueryWrapper<OldFansInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OldFansInfoEntity::getOpenId,openId);
        OldFansInfoEntity one = oldFansInfoService.getOne(queryWrapper);
        log.info("获得历史客户的福分信息：{}",JSONObject.toJSONString(one));
        if(null == one){
            return ApiRes.ok("该客户不存在历史福分");
        }else{
            if(0 == one.getScore()){
                return ApiRes.ok("该客户无须同步福分");
            }
            if(1== one.getState()){
                LambdaQueryWrapper<OldFansInfoEntity> queryWrapperOldFans = new LambdaQueryWrapper<>();
                queryWrapperOldFans.eq(OldFansInfoEntity::getFansId,fansId);
                OldFansInfoEntity oldFansInfo = oldFansInfoService.getOne(queryWrapperOldFans);
                if(null == oldFansInfo){
                    oldFansInfoService.oldScoreMove(one,agentScoreByAgentNo.getAgentScoreId(), fansId, appId);
                }
            }
        }
        return ApiRes.ok("历史福分已迁移完成");
    }

}
